<template>
  <div v-loading="infoLoading">
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="98%"
      top="20px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <el-form ref="postForm" :model="postForm" class="form-container" label-width="100px" :rules="rules">
        <!-- <el-form-item key="dbdw" prop="dbdw" label="单位">
          {{ postForm.dbdw }}
        </el-form-item>
        <el-form-item key="bdbdw" prop="bdbdw" label="被督办单位">
          {{ postForm.bdbdw }}
        </el-form-item> -->
        <el-form-item key="dbsj" prop="dbsj" label="时间">
          <el-date-picker v-if="!readOnly&&!doflag" v-model="postForm.dbsj" style="width:200px" value-format="yyyy-MM-dd" />
          <span v-else>{{ postForm.dbsj }}</span>
        </el-form-item>
        <el-form-item key="dbqx" prop="dbqx" label="办理期限">
          <div v-if="!readOnly&&!doflag"><el-input-number v-model="postForm.dbqx" style="width:200px" /> 天（0天代表无限制）</div>
          <span v-else>{{ postForm.dbqx!=='0'?postForm.dbqx+'天':'无' }}</span>
        </el-form-item>
        <el-form-item key="dbsx&&!doflag" prop="dbsx" label="事项">
          <el-input v-if="!readOnly&&!doflag" v-model="postForm.dbsx" type="textarea" :rows="10" style="width:90%" />
          <span v-else>{{ postForm.dbsx }}</span>
        </el-form-item>
        <upload-files v-if="!infoLoading" :cfajbh="postForm.id?postForm.id.toString():postForm.id" :read-only="readOnly1" table="bus_sub_db" :timestamp="timestamp1" :flag="1" @updateFj="updateFj1" />
        <el-form-item key="bdbdwid" prop="bdbdwid" label="被督办单位">
          <el-select v-if="!readOnly&&!doflag" v-model="postForm.bdbdwid" placeholder="请选择" style="width:200px;">
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.unitName"
              :value="item.id"
            />
          </el-select>
          <span v-else>{{ postForm.bdbdw }}</span>
        </el-form-item>
        <el-form-item key="blsj" prop="blsj" label="办结时间">
          <el-date-picker v-if="!readOnly||doflag" v-model="postForm.blsj" style="width:200px" value-format="yyyy-MM-dd" />
          <span v-else>{{ postForm.blsj }}</span>
        </el-form-item>
        <el-form-item key="bljg" prop="bljg" label="办理结果">
          <el-input v-if="!readOnly||doflag" v-model="postForm.bljg" type="textarea" :rows="10" style="width:90%" />
          <span v-else>{{ postForm.bljg }}</span>
        </el-form-item>
        <upload-files v-if="!infoLoading" :cfajbh="postForm.id?postForm.id.toString():postForm.id" :read-only="readOnly2" table="bus_sub_db" :timestamp="timestamp1" :flag="2" @updateFj="updateFj2" />
        <el-form-item key="submit" style="margin:10px 0">
          <el-button v-if="!readOnly" type="primary" :loading="loading" @click="submitForm">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <h2>工作进展情况</h2>
    <el-table
      ref="processTable"
      :data="processList"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :loading="processListLoading"
    >
      <el-table-column align="center" type="index" label="序号" width="50" />
      <el-table-column align="center" prop="dbrxm" label="姓名" width="80" />
      <!-- <el-table-column align="center" prop="dbdw" label="单位" width="150" /> -->
      <el-table-column align="center" prop="bdbdw" label="被督办单位" width="150" />
      <el-table-column align="center" prop="dbsj" label="时间" width="95" />
      <el-table-column align="center" prop="dbqx" label="办理期限" width="80">
        <template slot-scope="scope">
          {{ scope.row.dbqx==='0'?'无':scope.row.dbqx+'天' }}
        </template>
      </el-table-column>
      <el-table-column prop="dbsx" label="事项" min-width="300">
        <template slot-scope="scope">
          <div v-html="scope.row.dbsx?scope.row.dbsx.replace(/\n/g,'<br>'):''" />
        </template>
      </el-table-column>
      <el-table-column align="center" prop="blsj" label="办结时间" width="95" />
      <el-table-column prop="bljg" label="办理结果" min-width="100">
        <template slot-scope="scope">
          <div v-html="scope.row.bljg?scope.row.bljg.replace(/\n/g,'<br>'):''" />
        </template>
      </el-table-column>
      <el-table-column align="center" width="340">
        <template slot="header">
          <el-button
            v-if="canAdd"
            type="success"
            @click="add"
          >新增</el-button>
        </template>
        <template slot-scope="scope">
          <el-button
            @click="detail(scope.row.id)"
          >查看</el-button>
          <el-button
            v-if="userid===scope.row.dbrid"
            type="primary"
            @click="handleEdit(scope.row.id)"
          >修改</el-button>
          <el-button
            v-if="unitId===scope.row.bdbdwid"
            type="success"
            @click="handleDo(scope.row.id)"
          >办理</el-button>
          <!-- <el-button
            @click="handleDo(scope.row.id)"
          >办理</el-button> -->
          <!-- <el-popconfirm title="确定删除该项目吗？" style="margin-left:5px;"> -->
          <el-button
            v-if="userid===scope.row.dbrid"
            slot="reference"
            type="danger"
            @click="handleDelete(scope.row.id)"
          >删除</el-button>
          <!-- </el-popconfirm> -->
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import uploadFiles from './uploadfiles.vue'
const defaultForm = {
  dbdw: '',
  bdbdw: '',
  bdbdwid: null,
  dbsj: '',
  dbqx: '',
  dbsx: '',
  blsj: '',
  bljg: '',
  id: null
}
export default {
  name: 'Supervice',
  components: { uploadFiles },
  props: {
    cfajbh: {
      type: String,
      default: ''
    },
    timestamp: {
      type: Number,
      default: 0
    },
    businessTable: {
      type: String,
      default: ''
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === null || value === undefined || value === '') {
        // this.$message({
        //   message: '请将表单填写完整',
        //   type: 'error'
        // })
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      readOnly1: true,
      readOnly2: true,
      timestamp1: null,
      messageType: null,
      doflag: false,
      readOnly: true,
      unitId: 0,
      userid: 0,
      operation: '',
      canAdd: false,
      canFeedback: false,
      dialogVisible: false,
      dialogTitle: '新增',
      myHeaders: {},
      infoLoading: false,
      postForm: Object.assign({}, defaultForm),
      loading: false,
      rules: {
        dbsx: [{ validator: validateRequire }]
      },
      tempRoute: {},
      processListLoading: false,
      unitList: [],
      fjList1: [],
      fjList2: [],
      processList: [
        // { time: '第一次', unit1: '处非办', unit2: '公安局', date: '2021-05-10', limit: '10天', item: '尽快办理', result: '已办结' },
        // { time: '第二次', unit1: '处非办', unit2: '公安局', date: '2021-05-20', limit: '10天', item: '尽快办理', result: '已办结' }
      ]
    }
  },
  watch: {
    cfajbh: {
      handler(val, oldVal) {
        if (this.$refs['postForm']) {
          this.$refs['postForm'].resetFields()
        }
        if (this.cfajbh) {
          this.getData()
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
    // if (JSON.parse(localStorage.getItem('user')).unitName === '处非办' || JSON.parse(localStorage.getItem('user')).unitName === '督查室' || JSON.parse(localStorage.getItem('user')).unitName === '政法委') {
    this.canAdd = true
    // }
  },
  created() {
    this.getUnitList()
    const user = JSON.parse(localStorage.getItem('user'))
    this.userid = user.id
    this.unitId = user.unitId
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    updateFj1(list) {
      this.fjList1 = list
    },
    updateFj2(list) {
      this.fjList2 = list
    },
    checkCanFeedback(unitName) {
      return JSON.parse(localStorage.getItem('user')).unitName === unitName
    },
    add0(m) {
      return m < 10 ? '0' + m : m
    },
    handleDelete(id) {
      console.log(id)
      this.$http
        .get('/api/busSubDb/remove?id=' + id)
        .then(response => {
          if (response.data.success === true) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getData()
          } else {
            console.log('删除失败:' + response.data.message)
            this.$message({
              message: '删除失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    detail(id) {
      this.doflag = false
      this.$http
        .get('/api/busSubDb/getById?id=' + id)
        .then(response => {
          if (response.data.success === true) {
            this.postForm = response.data.result
            this.timestamp1 = new Date().getTime()
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '删除失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
      console.log(id)
      this.dialogVisible = true
      this.dialogTitle = '查看'
      this.readOnly = true
      this.readOnly1 = true
      this.readOnly2 = true
    },
    handleEdit(id) {
      this.doflag = false
      this.$http
        .get('/api/busSubDb/getById?id=' + id)
        .then(response => {
          if (response.data.success === true) {
            this.postForm = response.data.result
            this.timestamp1 = new Date().getTime()
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '删除失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
      console.log(id)
      this.dialogVisible = true
      this.dialogTitle = '修改'
      this.readOnly = false
      this.readOnly1 = false
      this.readOnly2 = true
    },
    // 被督办单位办理时调用此接口
    handleDo(id) {
      this.messageType = 2 // 发消息时messageType=2为督办反馈
      this.$http
        .get('/api/busSubDb/getById?id=' + id)
        .then(response => {
          if (response.data.success === true) {
            this.postForm = response.data.result
            this.timestamp1 = new Date().getTime()
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '删除失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
      console.log(id)
      this.doflag = true
      this.dialogVisible = true
      this.dialogTitle = '办理'
      this.readOnly = false
      this.readOnly1 = true
      this.readOnly2 = false
    },
    feedback(item) {
      this.timestamp1 = new Date().getTime()
      this.operation = 'feedback'
      this.postForm = item
      this.dialogVisible = true
      this.dialogTitle = '办理'
    },
    add() {
      this.timestamp1 = new Date().getTime()
      this.readOnly = false
      this.operation = 'add'
      this.postForm = Object.assign({}, defaultForm)
      // this.postForm.dbdw = JSON.parse(localStorage.getItem('user')).unitName
      // switch (this.businessTable) {
      //   case 'bus_ga':
      //     this.postForm.bdbdw = '公安'
      //     this.postForm.bdbdwid = 2
      //     break
      //   case 'bus_hcdj':
      //     this.postForm.bdbdw = '公安'
      //     this.postForm.bdbdwid = 2
      //     break
      //   case 'bus_sfsj':
      //     this.postForm.bdbdw = '公安'
      //     this.postForm.bdbdwid = 2
      //     break
      //   case 'bus_ysscqs':
      //     this.postForm.bdbdw = '公安'
      //     this.postForm.bdbdwid = 2
      //     break
      //   case 'bus_cxa':
      //     this.postForm.bdbdw = '公安'
      //     this.postForm.bdbdwid = 2
      //     break
      //   case 'bus_qs':
      //     this.postForm.bdbdw = '检察院'
      //     this.postForm.bdbdwid = 3
      //     break
      //   case 'bus_sp':
      //     this.postForm.bdbdw = '法院'
      //     this.postForm.bdbdwid = 4
      //     break
      //   case 'bus_zx':
      //     this.postForm.bdbdw = '法院'
      //     this.postForm.bdbdwid = 4
      //     break
      // }
      this.dialogVisible = true
      this.dialogTitle = '新增'
      this.readOnly1 = false
      this.readOnly2 = true
    },
    getUnitList() {
      const para = {
        pageNum: 1,
        pageSize: 1000
      }
      this.$http
        .post('api/sysUnit/queryPage', para)
        .then(response => {
          if (response.data.success === true) {
            this.unitList = response.data.result.records
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getData() {
      this.processListLoading = true
      const para = {
        // businessTable: this.businessTable,
        cfajbh: this.cfajbh,
        pageNum: 1,
        pageSize: 1000
      }
      this.$http
        .post('api/busSubDb/queryByPage', para)
        .then(response => {
          this.processListLoading = false
          if (response.data.success === true) {
            this.processList = response.data.result.records
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.processListLoading = false
        })
    },
    businessTableText(businessTable) {
      const businessTableArray = [
        { table: 'bus_ga', text: '立案侦查' },
        { table: 'bus_hcdj', text: '核查登记' },
        { table: 'bus_sfsj', text: '司法审计' },
        { table: 'bus_ysscqs', text: '移送审查起诉' },
        { table: 'bus_cxa', text: '销撤并案' },
        { table: 'bus_qs', text: '审查起诉' },
        { table: 'bus_sp', text: '审判' },
        { table: 'bus_zx', text: '执行' },
        { table: 'bus_qt', text: '清退' },
        { table: 'bus_ww', text: '维稳' }
      ]
      const table = businessTableArray.find(item => item.table === businessTable)
      return table ? table.text : ''
    },
    submitForm(flag) {
      const day = new Date()
      day.setTime(day.getTime())
      // this.postForm.dbsj = day.getFullYear() + '-' + this.add0(day.getMonth() + 1) + '-' + this.add0(day.getDate())
      this.$refs.postForm.validate(valid => {
        if (valid) {
          let para = {}
          let url = ''
          para = {
            businessTable: this.businessTable,
            cfajbh: this.cfajbh,
            dbsj: this.postForm.dbsj,
            dbqx: this.postForm.dbqx,
            dbsx: this.postForm.dbsx,
            bdbdwid: this.postForm.bdbdwid,
            bdbdw: this.postForm.bdbdwid ? this.unitList.find(item => item.id === this.postForm.bdbdwid).unitName : '',
            bljg: this.postForm.bljg,
            blsj: this.postForm.blsj,
            id: this.postForm.id
          }
          // 处理发送消息
          if (this.postForm.bdbdwid) { // 填写了被督办单位
            if (this.messageType !== 2) { // 且不是督办反馈
              this.messageType = 1 // messageType=1时需要发送督办消息
            }
          } else {
            this.messageType = null
          }
          para.messageType = this.messageType
          if (this.messageType === 1) {
            para.content = '<b>环节：</b>' + this.businessTableText(this.businessTable) + '<br>'
            para.content = para.content + '<b>督办时间：</b>' + this.postForm.dbsj + '<br>'
            if (this.postForm.dbqx) {
              para.content = para.content + '<b>办理期限：</b>' + this.postForm.dbqx + '天<br>'
            }
            para.content = para.content + '<b>督办事项：</b><br>' + (this.postForm.dbsx ? this.postForm.dbsx.replace(/\n/g, '<br>') : '') + '<br>'
          }
          if (this.messageType === 2) {
            para.content = '<b>环节：</b>' + this.businessTableText(this.businessTable) + '<br>'
            para.content = para.content + '<b>督办时间：</b>' + this.postForm.dbsj + '<br>'
            if (this.postForm.dbqx) {
              para.content = para.content + '<b>办理期限：</b>' + this.postForm.dbqx + '天<br>'
            }
            para.content = para.content + '<b>督办事项：</b><br>' + (this.postForm.dbsx ? this.postForm.dbsx.replace(/\n/g, '<br>') : '') + '<br>'
            para.content = para.content + '<b>办结时间：</b>' + this.postForm.blsj + '<br>'
            para.content = para.content + '<b>办理结果：</b><br>' + (this.postForm.bljg ? this.postForm.bljg.replace(/\n/g, '<br>') : '') + '<br>'
          }
          if (this.messageType === 2) {
            para.files = this.fjList2.map(item => { return { fileId: item.id, remark: item.remark, classCode: item.classCode } })
          } else {
            para.files = this.fjList1.map(item => { return { fileId: item.id, remark: item.remark, classCode: item.classCode } })
          }
          // para.content
          url = '/api/busSubDb/saveDb'
          this.loading = true
          this.$http
            .post(url, para)
            .then(response => {
              this.loading = false
              if (response.data.success === true) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.dialogVisible = false
                this.getData()
                this.postForm = Object.assign({}, defaultForm)
                this.loading = false
              } else {
                console.log('操作失败:' + response.data.message)
                this.$message({
                  message: '操作失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(error => {
              console.log(error)
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
